﻿using IdentityModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading.Tasks;
using YXY.Identity.ApiResult;
using YXY.Identity.Model;
using YXY.Identity.Repository;
using YXY.Identity.Service.Filter;
using YXY.Identity.Service.HttpContextUser;
using YXY.Identity.Service.InputModel;
using YXY.Identity.Service.OutModel;

namespace YXY.Identity.Service.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : BaseController
    {
        private readonly ILogger<AccountController> _logger;
        private readonly UserRepository _userRepository = new UserRepository();
        private readonly RoleRepository _roleRepository = new RoleRepository();
        private readonly TokenRepository _tokenRepository = new TokenRepository();

        public AccountController(ILogger<AccountController> logger, IHttpContextUser httpContextUser) : base(httpContextUser)
        {
            _logger = logger;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(ValidateAdminActionFilter))]
        public async Task<CommonResult> AddUser([FromBody] InputModelUserAdd input)
        {
            var model = ExpressionGenericMapper<InputModelUserAdd, UserModel>.Trans(input);

            var exists =await _userRepository.GetFirstAsync(c => c.Phone.Equals(model.Phone));
            if (exists != null)
            {
                return ApiRespHelp.getError(-100, "添加失败，可能存在相同手机号！");
            }

            var roleExists = await _roleRepository.GetFirstAsync(c => c.Id == model.RoleId);
            if (roleExists != null)
            {
                return ApiRespHelp.getError(-101, "未找到对应角色");
            }

            if (await _userRepository.InsertAsync(model))
            {
                return ApiRespHelp.getSuccess("添加成功");
            }
            return ApiRespHelp.getError();
        }
        /// <summary>
        /// 用户登录  ※  JWT
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<CommonResult> JWTLogin([FromBody] InputModelUserLogin input)
        {
            TokenProvider tokenProvider = new TokenProvider();
            //初始化 声明对象
            var claimsIdentity = new ClaimsIdentity(new Claim[] {
                new Claim(JwtClaimTypes.Audience, JwtOption.Audience) ,
                new Claim(JwtClaimTypes.Issuer, JwtOption.Issuer),
                new Claim(JwtClaimTypes.Subject, GrantType.Password)
            });
            var user = await _userRepository.GetFirstAsync(s => s.Phone.Equals(input.Phone) && s.Password.Equals(input.Password));
            if (user != null)
            {
                //添加声明对象
                claimsIdentity.AddClaim(new Claim(JwtClaimTypes.Id, user.Id.ToString()));
                claimsIdentity.AddClaim(new Claim(JwtClaimTypes.Role, user.RoleId.ToString()));
                claimsIdentity.AddClaim(new Claim(JwtClaimTypes.Name, user.Phone));
                var token = tokenProvider.BulidToken(claimsIdentity);
                TokenModel tokenModel = new TokenModel()
                {
                    AccessToekn = token.AccessToken,
                    ClientType = "JWT授权",
                    Expires = token.ExpiresIn,
                    Phone = user.Phone,
                };
                await _tokenRepository.InsertAsync(tokenModel);
            }
            else
            {
                return ApiRespHelp.getError(-100, "账号或密码错误");
            }
            return ApiRespHelp.GetApiData(tokenProvider.BulidToken(claimsIdentity));
        }
        /// <summary>
        /// 用户登录  ※ ID4
        /// </summary> 
        /// <returns></returns>
        [HttpPost]
        public async Task<CommonResult> ID4Login([FromBody] InputModelUserLogin input)
        {
            //string url = "https://localhost:44318/connect/token";
            return ApiRespHelp.getSuccess();
        }

        /// <summary>
        /// 获取当前用户登录角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<CommonResult> GetUserInfo()
        {
            var userInfo = _httpContextUser.GetUserInfo();
            var result = "";
            switch (userInfo.RoleId)
            {
                case 1:
                    result = "超级管理员";
                    break;
                case 2:
                    result = "管理员";
                    break;
                case 3:
                    result = "普通用户";
                    break;
                default:
                    break;
            }
            return ApiRespHelp.GetApiData(result);
        }

        /// <summary>
        /// 获取Token列表  ※  管理员角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(ValidateAdminActionFilter))]
        public async Task<PageResult<OutModelToken>> GetTokenPage([FromForm] InputModelTokenList input)
        {
            Expression<Func<TokenModel, bool>> where = m => 0 == 0;
            var list = await _tokenRepository.GetPageListAsync(where, new SqlSugar.PageModel() { PageSize = input.PageSize, PageIndex = input.CurrentPageIndex });
            var result = ExpressionGenericMapper<TokenModel, OutModelToken>.TransList(list);
            result = result.OrderByDescending(s=>s.CreateTime).ToList();
            return ApiRespHelp.getApiDataListByPage(result, list.Count, input.CurrentPageIndex, input.PageSize);
        }
    }
}
